#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdbool.h>

//#define PORT 1234
#define BUFFER_SIZE 1024

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("请指定参数：端口号\n");
        return 1;
    }

    const char *port_i = argv[1];
	 int PORT = atoi(port_i);

    int server_fd, new_socket;
    struct sockaddr_in address;
    int addrlen = sizeof(address);
    char buffer[BUFFER_SIZE] = {0};
    char reply[BUFFER_SIZE] = {0};

    // 创建套接字
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 设置地址信息
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    // 绑定套接字到指定地址和端口
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // 监听传入的连接
    if (listen(server_fd, 3) < 0) {
        perror("listen failed");
        exit(EXIT_FAILURE);
    }

    // 等待接收连接
    if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) {
        perror("accept failed");
        exit(EXIT_FAILURE);
    }

    char end_command[] = "quit\n";
    bool send_end_command = false;

    // 接收和处理消息
    int valread;
    read(new_socket, buffer, BUFFER_SIZE);
    printf("connected: %s\n", buffer);
    while ((valread = read(new_socket, buffer, BUFFER_SIZE)) > 0) {
        if (strcmp(buffer, end_command) == 0) {
            //send_end_command = true;
            break;
        }else{
            printf("Received message: %s", buffer);
        }

        //printf("Received message: %s\n", buffer);

        // 读取回复输入
        printf("reply: ");
        fgets(buffer, BUFFER_SIZE, stdin);

        // 检查是否输入结束指令
        if (strcmp(buffer, end_command) == 0) {
            send_end_command = true;
        }


        // 发送回复
        if (send(new_socket, buffer, strlen(buffer), 0) < 0) {
            perror("send failed");
            exit(EXIT_FAILURE);
        }

        if (send_end_command) {
            break;
        }

        memset(buffer, 0, BUFFER_SIZE);
    }

    // 关闭套接字
    close(new_socket);
    close(server_fd);

    return 0;
}
